<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Config;
use Request;
use App\Exceptions\ThrowException;
use App\Libraries\wxBizDataCrypt;
use Illuminate\Support\Facades\Redis;
use DB;

class BaseController extends Controller
{


    private $appId = 'wx96ec1c1a5f605b07';
    private $appSecret = 'ff6dce27ec4fd4076a8c50c92ba5ae46';

    public function __construct(){

    }


    //获取用户信息
    public function getUserInfo(){
        $userInfo = $this->userInfo();
        $userId = !empty($userInfo['user_id'])?$userInfo['user_id']:0;
        $user_info = DB::table('user')->where('user_id',$userId)->first();
        return $user_info;
    }

    // 获取用户token存储于redis的用户信息
    public function userInfo($userToken='',$field=''){

        $redish = Config::get('key.redishkey');
        $request = $this->requestAll();
        $header  = $_SERVER;
        if(empty($userToken)){
            //= '64b2fc2fb62898db401db5074bd8b12d'
            if(isset($request['user_token'])){
                $userToken = $request['user_token'];
            }elseif(isset($header['HTTP_TOKEN'])){
                $userToken = $header['HTTP_TOKEN'];

            }elseif(isset($request['token'])){
                $userToken = $request['token'];

            }elseif(isset($request['formData']['user_token'])){
                $userToken = $request['formData']['user_token'];

            }
        }
        $userInfo = $this->redis()->hget($redish,$userToken);
        if( empty($userInfo) ){
            return $this->jsonResult('401',$request,'登录失效，请重新登录');
        }

        $userInfoArr = json_decode($userInfo,true);
        if(empty($userInfoArr) ){
            return $this->jsonResult('401',$request,'登录失效，请重新登录');
        }

        return !empty($field) && isset($userInfoArr[$field]) ? $userInfoArr[$field] : $userInfoArr;
    }


    public function jsonResult($code, $data = '', $message = '',$field=[])
    {
        header('content-type:application:json;charset=utf8');
        header("Access-Control-Allow-Origin:*");
        header('Access-Control-Allow-Methods:*');
        header('Access-Control-Allow-Headers:*');
        $errorInfo = Config::get('error.errorCode');
        if (empty($message)) {
            $message = isset($errorInfo[$code]);
        }
        $result = array(
            'code' => $code,
            'msg' => $message,
            'data' => $data,
        );
        //添加附加字段
        if(!empty($field)){
            foreach ($field as $k=>$v){
                $result[$k] = $v;
            }
        }

        echo json_encode($result);
        exit(1);

    }


    //获取redis 对象
    public function redis($redisConnectTag = 'default'){
        return Redis::connection($redisConnectTag);
    }


    //获取request
    public function requestAll(){

        $request = Request::all();

        return $request;
    }

    //发送短信
    public function sendSms($phone) {
        $code =random(4);

        $params = array();
        $url ='http://115.28.50.135:8888/sms.aspx';
        $content = '【医竞采】手机动态验证码'.$code.'，如非本人操作请忽略此短信。';

        $params=[
            'userid'=>'4259',
            'account'=>'北京医麦科技',
            'password'=>'123456',
            'mobile'=>$phone,
            'content'=>$content,
            'sendTime'=>'',
            'action'=>'send',
            'extno'=>'',
        ];
        $sms = [
            'code'=>$code,
            'phone'=>$phone,
            'is_use'=>0
        ];
        $rs = http_request($url,$params);
        $arr = xmlToArray($rs);
        if($arr['returnstatus']== 'Success'){
          return DB::table('sms')->insertGetId($sms);
        }

    }
    //发送通知短信
    public function bidSendSms($phone,$content) {

        $params = array();
        $url ='http://115.28.50.135:8888/sms.aspx';
        $content = $content;

        $params=[
            'userid'=>'4259',
            'account'=>'北京医麦科技',
            'password'=>'123456',
            'mobile'=>$phone,
            'content'=>$content,
            'sendTime'=>'',
            'action'=>'send',
            'extno'=>'',
        ];

        $rs = http_request($url,$params);
        $arr = xmlToArray($rs);
        if($arr['returnstatus']== 'Success'){
            return true;
        }

    }
    //获取手机号
    public function getPhoneByCode($encryptedData,$iv,$code,$grant_type='authorization_code'){
        //登录凭证不能为空
        if ($code == null || strlen($code) == 0) {
            $this->jsonResult(1001,'','code 不能为空');
        }

        //获取微信配置
        $AppID = $this->appId;
        $AppSecret = $this->appSecret;

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$AppID.'&secret='.$AppSecret.'&js_code='.$code.'&grant_type='.$grant_type;
        $getPhoneTicket = http_request($url);
        $getPhoneTicketArr = json_decode($getPhoneTicket,true);
        //openid,session_key,unionid

        if(!isset($getPhoneTicketArr['session_key'])){
            $this->jsonResult(1001);


        }
        $pc = new wxBizDataCrypt($AppID, $getPhoneTicketArr['session_key']);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);


        if ($errCode !== 0) {
            $this->jsonResult(1001);
        }

        $data = json_decode($data,true);

        $data['openid'] = $getPhoneTicketArr['openid'];

        return $data;

    }

    //获取SessionKey
    public function getSessionKeyByCode($request){
         $code = $request['code'];
         $encryptedData = $request['encryptedData'];
         $iv = $request['iv'];
         $udata = $request['udata'];
         $uiv = $request['uiv'];


        //登录凭证不能为空
        if ($code == null || strlen($code) == 0) {
            $this->jsonResult(1001,'','code 不能为空');
        }

        //获取微信配置
        $AppID = $this->appId;
        $AppSecret = $this->appSecret;

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$AppID.'&secret='.$AppSecret.'&js_code='.$code.'&grant_type=authorization_code';
        $getPhoneTicket = http_request($url);
        $getPhoneTicketArr = json_decode($getPhoneTicket,true);

        if(!isset($getPhoneTicketArr['session_key'])){
            $this->jsonResult(1002,'');

        }
        $pc = new wxBizDataCrypt($AppID, $getPhoneTicketArr['session_key']);
        $errCode = $pc->decryptData($udata, $uiv, $data);

        if ($errCode !== 0) {
            $this->jsonResult(1001);
        }
        $data = json_decode($data,true);

        return $data;

    }
    //获取公众号access_token
    public function getAccessToken(){

        $date = date('Y-m-d H:i:s',(time()*100-7000*100)/100);
        $token = DB::table('token')->where('key','access_token')->first();
        if(!empty($token) && $token['up_time'] > $date){
            return $token['val'];
        }else{
            $accessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx811c224bf219752a&secret=5df5ee56f259eff277c8a8688ec64796';
            $accessTokenRst = json_decode(http_request($accessTokenUrl), true);
            if (!empty($accessTokenRst['access_token'])) {
                if(!empty($token)) {
                    DB::table('token')->where('key','access_token')->update(['val'=>$accessTokenRst['access_token']]);
                }else{
                    DB::table('token')->insertGetId(['key'=>'access_token','val'=>$accessTokenRst['access_token']]);
                }
                return $accessTokenRst['access_token'];
            }
        }
    }

    //获取JsApiTicket
    public function getJsApiTicket(){
        $access_token = $this->getAccessToken();
        $date = date('Y-m-d H:i:s',(time()*100-7000*100)/100);
        $ticket = DB::table('token')->where('key','jsapi_ticket')->first();
        if(!empty($ticket) && $ticket['up_time'] > $date){
            return $ticket['val'];
        }else{
            $ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
            $ticketRst = json_decode(http_request($ticketUrl), true);
            if (!empty($ticketRst['ticket'])) {
                if(!empty($token)) {
                    DB::table('token')->where('key','jsapi_ticket')->update(['val'=>$ticketRst['ticket']]);
                }else{
                    DB::table('token')->insertGetId(['key'=>'jsapi_ticket','val'=>$ticketRst['ticket']]);
                }
                return $ticketRst['ticket'];
            }
        }

    }
    //获取jsSdkSign
    public function getJsSdkSign(){
        $jsapi_ticket = $this->getJsApiTicket();
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $noncestr = create_randomstr();
        $timestamp = time();

        $string1 = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$noncestr."&timestamp=".$timestamp."&url=".$url;
        $signature = sha1($string1);
        $signPackage = array(
            'appId'   => 'wx811c224bf219752a',
            'nonceStr' => $noncestr,
            'timestamp' => $timestamp,
            'signature' => $signature,
        );
        return $signPackage;

    }


}
